#!/bin/sh

# code inspired by the app "Mobile HotSpot"
# this is incompatible with the libnat64 library

INTERFACE="usb0"
NETWORK="10.255.255"

PREFIX=`/sbin/ip -6 addr show scope global dev gprs0 | awk '/inet6/ { print $2}'| head -1 |sed s@/.*@@`

if [ -z "$PREFIX" ]; then
  echo no ipv6 connection detected
  exit 1
fi

if [ -z "$1" ]; then
  echo 'this script takes one argument: "start" or "stop"'
  exit 1
fi

if [ "$1" == "start" ]; then
  ifconfig $INTERFACE up

  ifconfig $INTERFACE $NETWORK.129 netmask 255.255.255.128
  ip addr add $PREFIX/64 dev $INTERFACE

  /usr/sbin/dnsmasq -i $INTERFACE \
        -a $NETWORK.129 \
        -I lo -z -x /var/run/dnsmasq.$INTERFACE.pid \
	--dhcp-range=$NETWORK.130,$NETWORK.200,6h \
	--dhcp-option=3,$NETWORK.129 \
	--dhcp-option=6,$NETWORK.129

  echo 1 >/proc/sys/net/ipv6/conf/all/forwarding

  cat <<EOF >/etc/radvd.conf.$INTERFACE
interface $INTERFACE {
  MinRtrAdvInterval 3;
  MaxRtrAdvInterval 10;
  AdvLinkMTU 1400;
  AdvSendAdvert on;
  prefix $PREFIX/64
  {
    AdvOnLink on;
    AdvAutonomous on;
    AdvValidLifetime 300;
    AdvPreferredLifetime 120;
  };
};
EOF

  /usr/sbin/radvd -C /etc/radvd.conf.$INTERFACE -p /var/run/radvd.pid
elif [ "$1" == "stop" ]; then
  kill `cat /var/run/radvd.pid /var/run/dnsmasq.$INTERFACE.pid`
  ifconfig $INTERFACE down
  echo 0 >/proc/sys/net/ipv6/conf/all/forwarding
else
  echo unknown argument: $1
  exit 1
fi
